package cn.yr.common.exception;


import cn.yr.common.exception.exception.base.BaseException;
import cn.yr.common.exception.ret.Ret;
import cn.yr.common.exception.ret.RetCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * @author Lang 1102076808@qq.com
 * @description 全局异常处理
 * @date 2020-06-22 22:07
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

	@ExceptionHandler(RuntimeException.class)
	public Ret handleAppException(RuntimeException exception) {
		if(exception instanceof BaseException){
			BaseException baseException = (BaseException)exception;
			log.debug(baseException.getMessage());
			return	baseException.getRet();
		}
		/** 未知的异常抛出来 */
		exception.printStackTrace();
		return Ret.error(RetCode.SYS_ERROR);
	}

	/**
	 * 所有验证框架异常捕获处理
	 * @return
	 */
	@ExceptionHandler(value = {BindException.class, MethodArgumentNotValidException.class})
	public Object validationExceptionHandler(Exception exception) {
		BindingResult bindResult = null;
		if (exception instanceof BindException) {
			bindResult = ((BindException) exception).getBindingResult();
		} else if (exception instanceof MethodArgumentNotValidException) {
			bindResult = ((MethodArgumentNotValidException) exception).getBindingResult();
		}
		String msg;
		if (bindResult != null && bindResult.hasErrors()) {
			msg = bindResult.getAllErrors().get(0).getDefaultMessage();
			if (msg.contains("NumberFormatException")) {
				msg = "参数类型错误！";
			}
		}else {
			msg = "系统繁忙，请稍后重试...";
		}
		return Ret.error(msg);
	}

	@ExceptionHandler(NoHandlerFoundException.class)
	public Ret noHandlerFoundException(NoHandlerFoundException exception) {
		Ret ret = Ret.error(RetCode.RESOURCE_NOT_FOUND);
		log.debug(RetCode.RESOURCE_NOT_FOUND.getMessage());
		log.debug(exception.getMessage());
		return ret;
	}

	/**
	 * @description 捕获shiro异常
	 * @date 2020-06-24 9:26
	 */
	/*@ExceptionHandler(ShiroException.class)
	public Ret handleShiroException(ShiroException exception) {

		*//** 授权异常 *//*
		if(exception instanceof AuthorizationException){
			Ret ret = Ret.error(RetCode.REQUEST_AUTHORIZATION_ERROR);
			log.info(RetCode.REQUEST_AUTHORIZATION_ERROR.getMessage());
			return ret;
		}

		*//** 认证异常 *//*
		if(exception instanceof AuthenticationException){
			Ret ret = Ret.error(RetCode.REQUEST__AUTHENTICATION__ERROR);
			log.debug(RetCode.REQUEST__AUTHENTICATION__ERROR.getMessage());
			return ret;
		}
		Ret ret = Ret.error(RetCode.REQUEST_SHIRO_ERROR);
		log.debug(RetCode.REQUEST_SHIRO_ERROR.getMessage());
		return ret;
	}*/
}
